package com.busi.ecCommplete;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Date;
import java.util.Map;

import com.busi.utils.CertificateCoder;
import com.busi.utils.DHCoderUtil;
import com.jfinal.upload.UploadFile;
import com.zcurd.common.util.DateUtil;
import com.zcurd.common.util.StringUtil;

public class EcCommpleteService {

	private static final String tempPath = "/Users/mapeixu/Documents/decrypt/";

	public void uploadFile(UploadFile file, EcCommplete model, int ecType) {
		String fileName = file.getFileName();
		int index = fileName.lastIndexOf(".");
		String fileType = fileName.substring(index + 1);
		String saveName = DateUtil.dateToString(new Date(), "yyyyMMddHHmmss") + StringUtil.randomNumber() + ".ec";
		// windows路径
		// String newFilePath = file.getUploadPath() + "\\" + saveName;
		// mac linux 路径
		String newFilePath = file.getUploadPath() + "/" + saveName;
		File delfile = new File(newFilePath);
		// 非对称加密
		File encrypt = CertificateCoder.encryptFile(file.getFile(), delfile);
		File destFileName = new File(newFilePath + "dh");
		Map<String, Object> dhStr = DHCoderUtil.encrypt(encrypt, destFileName);
		delfile.delete();
		// 签名
		String sign = CertificateCoder.sign((byte[]) dhStr.get("content"));
		file.getFile().delete();
		model.set("save_path", dhStr.get("filePath"));
		model.set("ec_type", ecType);
		model.set("name", fileName);
		model.set("type", fileType);
		model.set("sign", sign);
		model.set("key1", dhStr.get("key1"));
		model.set("key2", dhStr.get("key2"));
		model.save();
		System.out.println("----------------上传文件路径：" + delfile.getPath());
	}

	public File downloadFile(EcCommplete ec) {
		// 读取文件内容
		String filePath = ec.getStr("save_path");
		File sourceFile = new File(filePath);
		String path = tempPath + DateUtil.dateToString(new Date(), "yyyyMMddHHmmss") + StringUtil.randomNumber();
		File decryptFile = new File(path);
		// 验签
		String sign = ec.getStr("sign");
		boolean b = false;
		try {
			b = CertificateCoder.verify(Files.readAllBytes(sourceFile.toPath()), sign);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (!b)
			return null;
		// DH解密（解封）
		File dhContent = DHCoderUtil.decrypt(sourceFile, decryptFile, ec.getStr("key2"));
		// RSA解密（非对称解密）
		File rsaDecryptFile = new File(path + ".rsa");
		File decrypt = CertificateCoder.decryptFile(dhContent, rsaDecryptFile);
		dhContent.delete();
		return decrypt;
	}
}
